<?php
class User extends CI_Controller {
    function __construct() {
        parent::__construct ();
        $this->load->model ( 'User_Model' );
    }
    
    function list_user() {
        $this->load->library ( 'pagination' );
        $this->load->helper ( 'url' );

        $data ['data'] = $this->User_Model->list_all ();
        
        // load view
        $this->load->view ( 'common/header', $data );
        $this->load->view ( 'list_user', $data );
        $this->load->view ( 'common/footer', $data );
    }
    function api_login() {
        try {
            $post_params = $this->input->post ();
            $params = json_decode ( $post_params ['params'], true );
            if (isset ( $params ['username'] ) && isset ( $params ['password'] )) {
                $username = $params ['username'];
                $password = $params ['password'];
                $login_info = $this->User_Model->api_login ( $username, $password );
                if (null!=$login_info) {
                    $this->set_infor ("normal", "true", $login_info);
                } else {
                    $this->set_output ( "normal", "false" );
                }
            } else {
                $this->set_output ( "normal", "false" );
            }
        } catch ( Exception $ex ) {
            $this->set_output ( "abnormal", "false" );
        }
    }
    private function set_output($status, $result) {
        $this->output->set_content_type ( 'application/json' )->set_output ( json_encode ( array (
                "status" => $status,
                "result" => $result 
        ) ) );
    }
    private function set_infor($status, $result, $login_info) {
        $this->output->set_content_type ( 'application/json' )->set_output ( json_encode (
        	array(
        	        "status" => $status,
        	        "result" => $result,
        	        "infor"  => $login_info
            )
        ) );
    }
    function user_profile($user_id) {
        $data = null;
        $data = $this->User_Model->get_by_id ( $user_id );
        $this->load->view ( 'common/header' );
        $this->load->view ( 'user_profile', array (
                'data' => $data [0] 
        ) );
        $this->load->view ( 'common/footer' );
    }
    function edit_user($user_id) {
        $data = null;
        if ($this->input->server ( 'REQUEST_METHOD' ) == 'GET') {
            $data = $this->User_Model->get_by_id ( $user_id );
            $this->load->view ( 'common/header' );
            $this->load->view ( 'edit_user', array (
                    'data' => $data [0] 
            ) );
            $this->load->view ( 'common/footer' );
        } else {
            $this->load->library('form_validation');
            $data = array();
            if ($this->form_validation->run('user/edit_user') === FALSE)
            {
                $this->form_validation->set_error_delimiters('<div class="error" style="color:red">', '</div>');
                $data = $this->User_Model->get_by_id ( $user_id );
                $this->load->view ( 'common/header' );
                $this->load->view ( 'edit_user', array (
                    'data' => $data [0]
                ) );
                $this->load->view ( 'common/footer' );
            } else {
				$update_user_data = $this->input->post ();
				// var_dump($update_user_data);die;
				$update_results = $this->User_Model->update ( $user_id, $update_user_data );
				if ($update_results) {
					$this->session->set_flashdata ( 'success', 'ユーザ更新成功' );
					redirect ( $this->config->base_url ( 'index.php/user' ) );
				} else {
					$this->session->set_flashdata ( 'unsuccess', 'ユーザ更新失敗' );
					redirect ( $this->config->base_url ( 'index.php/user/edit_user' ) . "/" . $user_id );
				}
            }
        }
    }
    function change_login_info($user_id) {
        $data = null;
        if ($this->input->server ( 'REQUEST_METHOD' ) == 'GET') {
            $data = $this->User_Model->get_by_id ( $user_id );
            $this->load->view ( 'common/header' );
            $this->load->view ( 'edit_user', array (
                    'data' => $data [0] 
            ) );
            $this->load->view ( 'common/footer' );
        } else {
            $this->load->library('form_validation');
            $data = array();
            if ($this->form_validation->run('user/change_login_info') === FALSE)
            {
                $this->form_validation->set_error_delimiters('<div class="error" style="color:red">', '</div>');
				$data = $this->User_Model->get_by_id ( $user_id );
				$this->load->view ( 'common/header' );
				$this->load->view ( 'edit_user', array (
						'data' => $data [0], 
				        'tab'  => 2
				) );
				$this->load->view ( 'common/footer' );
            } else {
				$update_user_data = $this->input->post ();
				// var_dump($update_user_data);die;
				$update_results = $this->User_Model->change_login_info ( $user_id, $update_user_data );
				if ($update_results) {
					$this->session->set_flashdata ( 'success', 'ユーザのパスワード更新成功' );
					redirect ( $this->config->base_url ( 'index.php/user' ) );
				} else {
					$this->session->set_flashdata ( 'unsuccess', 'ユーザのパスワード更新失敗' );
					redirect ( $this->config->base_url ( 'index.php/user/edit_user' ) . "/" . $user_id );
				}
            }
        }
    }
    function create_user() {
        $data = null;
        if ($this->input->server ( 'REQUEST_METHOD' ) == 'GET') {
            $this->load->view ( 'common/header', $data );
            $this->load->view ( 'create_user', $data );
            $this->load->view ( 'common/footer', $data );
        } else {
            $this->load->library('form_validation');
            $data = array();
            if ($this->form_validation->run('user/create_user') === FALSE)
            {
                $this->form_validation->set_error_delimiters('<div class="error" style="color:red">', '</div>');
                $this->load->view ( 'common/header', $data );
                $this->load->view ( 'create_user', $data );
                $this->load->view ( 'common/footer', $data );
            } else {
                $create_user_data = $this->input->post ();
                // var_dump($create_user_data);die;
                $create_results = $this->User_Model->create ( $create_user_data );
                if ($create_results) {
                    $this->session->set_flashdata ( 'success', 'ユーザ作成成功' );
                    redirect ( $this->config->base_url ( 'index.php/user' ) );
                } else {
                    $this->session->set_flashdata ( 'unsuccess', 'ユーザ作成失敗' );
                    redirect ( $this->config->base_url ( 'index.php/user/create_user' ) );
                }
            }
        }
    }
    function delete_user() {
        if ($this->input->server ( 'REQUEST_METHOD' ) == 'POST') {
            $user_id = $this->input->post ( 'user_id' );
            $create_results = $this->User_Model->delete ( $user_id );
            if ($create_results) {
                $this->session->set_flashdata ( 'success', 'ユーザ削除成功' );
                redirect ( $this->config->base_url ( 'index.php/user' ) );
            } else {
                $this->session->set_flashdata ( 'unsuccess', 'ユーザ削除失敗' );
                redirect ( $this->config->base_url ( 'index.php/user' ) );
            }
        }
    }
    function csv_import() {
        $data = null;
        if ($this->input->server ( 'REQUEST_METHOD' ) == 'GET') {
            $this->load->view ( 'common/header', $data );
            $this->load->view ( 'csv_import', $data );
            $this->load->view ( 'common/footer', $data );
        } else {
            $config['upload_path'] = './resources/uploads/';
            $config['allowed_types'] = 'CSV|csv';
            $config['max_size']	= '10000';
            $this->load->library('upload', $config);
            $field_name = "importfile";
            if ( ! $this->upload->do_upload($field_name))
            {
                $error = array('error' => $this->upload->display_errors());
                $this->session->set_flashdata ( 'unsuccess', 'ウップロッド失敗' );
                redirect ( $this->config->base_url ( 'index.php/user/csv_import' ) );
            }
            else
            {
                //truncate table 
                $this->db->truncate('user');
                //Insert file info into database
                $data = array('upload_data' => $this->upload->data());
                $userfile = $data['upload_data']['file_name'];
                $filePath1 = './resources/uploads/';
                $filePath2 = $data['upload_data']['file_name'];
                $filePath = $filePath1 . $filePath2;
                $handle = fopen($filePath,'r');
                ini_set('auto_detect_line_endings',true);
                $index_line=0;
                while ( ($data = fgetcsv($handle) ) !== FALSE ) {
                    if($index_line!=0){
                        $import_data =array(
                                "company_name"=>mb_convert_encoding($data[1], mb_detect_encoding($data[1]), 'Shift_JIS'),
                                "username"=>mb_convert_encoding($data[2], mb_detect_encoding($data[2]), 'Shift_JIS'),
                                "zipcode"=>mb_convert_encoding($data[3], mb_detect_encoding($data[3]), 'Shift_JIS'),
                                "address1"=>mb_convert_encoding($data[4], mb_detect_encoding($data[4]), 'Shift_JIS'),
                                "address2"=>mb_convert_encoding($data[5], mb_detect_encoding($data[5]), 'Shift_JIS'),
                                "phone_number"=>mb_convert_encoding($data[6], mb_detect_encoding($data[6]), 'Shift_JIS'),
                                "mobile_number"=>mb_convert_encoding($data[7], mb_detect_encoding($data[7]), 'Shift_JIS'),
                                "fax"=>mb_convert_encoding($data[8], mb_detect_encoding($data[8]), 'Shift_JIS'),
                                "mail"=>mb_convert_encoding($data[9], mb_detect_encoding($data[9]), 'Shift_JIS'),
                                "store"=>mb_convert_encoding($data[10], mb_detect_encoding($data[10]), 'Shift_JIS'),
                                "store_phone_number"=>mb_convert_encoding($data[11], mb_detect_encoding($data[11]), 'Shift_JIS'),
                                "store_fax"=>mb_convert_encoding($data[12], mb_detect_encoding($data[12]), 'Shift_JIS'),
                                "store_mail"=>mb_convert_encoding($data[13], mb_detect_encoding($data[13]), 'Shift_JIS'),
                                "suzuka"=>mb_convert_encoding($data[14], mb_detect_encoding($data[14]), 'Shift_JIS'),
                                "suzuka_mail"=>mb_convert_encoding($data[15], mb_detect_encoding($data[15]), 'Shift_JIS'),
                                "login_name"=>mb_convert_encoding($data[16], mb_detect_encoding($data[16]), 'Shift_JIS'),
                                "login_password"=>mb_convert_encoding($data[17], mb_detect_encoding($data[17]), 'Shift_JIS')
                        );
                        $create_results = $this->User_Model->import ( $import_data );
                    }
                    $index_line++;
                }
                fclose($handle);
                ini_set('auto_detect_line_endings',FALSE);
                //change name
                rename($filePath, $filePath1.$filePath2.".BAK".date('YmdHis'));
                //redirect to list user
                $this->session->set_flashdata ( 'success', 'インポート成功' );
                redirect ( $this->config->base_url ( 'index.php/user/' ) );
            }
        }
    }
    function csv_export() {
        // Output file name
        $filename = "_user_export_". date("Ymd_His");
        // Header Conten
        $headerRow = array(
            '"No."',
            '"会社名 "',
            '"使用者名 "',
            '"郵便番号"',
            '"住所１"',
            '"住所２（マンション・ビル名）"',
            '"電話番号 "',
            '"携帯電話 "',
            '"ＦＡＸ番号 "',
            '"メールアドレス"',
            '"お取り扱い販売店名"',
            '"電話電話（販売店）"',
            '"ＦＡＸ番号（販売店）"',
            '"メールアドレス （お取り扱い販売店名）"',
            '"スズカ担当事業所"',
            '"メールアドレス （スズカ担当事業所）"',
            '"ログイン名"',
            '"パスワード"'
        );
        $rows = array();
        $data = $this->User_Model->export ();
        $index = 0;
        foreach ($data as $user){
            $row = array(
                    ++$index,
                    $user['company_name'],
                    $user['username'],
                    $user['zipcode'],
                    $user['address1'],
                    $user['address2'],
                    $user['phone_number'],
                    $user['mobile_number'],
                    $user['fax'],
                    $user['mail'],
                    $user['store'],
                    $user['store_phone_number'],
                    $user['store_fax'],
                    $user['store_mail'],
                    $user['suzuka'],
                    $user['suzuka_mail'],
                    $user['login_name'],
                    $user['login_password'],
            );
            $rows[] = $row;
        }
        // Build file
        $this->toCSV($headerRow, $rows, $filename);
        die();
    }
    /**
     * Output csv file
     *
     * @param array $header
     * @param array $data
     * @param string $filename
     */
    private function toCSV($header, $data, $filename) {
        header('Content-Encoding: UTF-8');
        $sep = ",";
        $eol = "\r\n";
        $csv = '';
        $csv .= count($header) ? implode($sep, $header) . $eol : '';
        if (!empty($data) && is_array($data)) {
            foreach ($data as $line) {
                $newline = array();
                foreach ($line as $element) {
                    $newline [] = '"' . $element . '"';
                }
                $csv .= implode($sep, $newline) . $eol;
            }
        }
        header('Content-Description: File Transfer');
        header('Content-Type: application/vnd.ms-excel');
        //        header('Content-Type: text/plain');
        header('Content-Disposition: attachment; filename=' . $filename . '.csv');
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . strlen($csv));
        echo trim(mb_convert_encoding($csv, 'sjis-win', 'UTF-8'));
        //        echo trim($csv);
        exit();
    }
}
?>